<template>
    <div class="" id="userMessage">
        <el-row  style="padding:60px 0 0 0;">
            <el-col :span="10" :offset="6" >
                <div class="permission-content bg-purple user-table" >
                    <el-form ref="formData" :model="message" :rules="Rules" label-width="80px" style="padding:20px 0 0 0">
                      <el-form-item >
                        <div class="avatar" >
                                <img :src="message.avatar" @click="imagecropperShow=true"  width="100%" alt="">   
                        </div>
                       
                      </el-form-item>
                      
                      <el-form-item label="用户名">
                        <el-input v-model.trim="message.userName"></el-input>
                      </el-form-item>
                      <!-- <el-form-item label="性别">
                        <el-input v-model.trim="message.sex"></el-input>
                      </el-form-item> -->
                      <el-form-item label="年龄">
                        <el-input v-model.trim="message.age"></el-input>
                      </el-form-item>
                      <el-form-item label="角色">
                        <el-input disabled v-model.trim="role[message.role]"></el-input>
                      </el-form-item>
                      <el-form-item label="所在地址">
                        <el-input v-model.trim="message.address"></el-input>
                      </el-form-item>
                       <el-form-item label="所属公司">
                        <el-input v-model.trim="message.company"></el-input>
                      </el-form-item>
                      <el-form-item label="手机号" prop="telPhone">
                        <el-input v-model.trim="message.telPhone" maxlength="11" clearable></el-input>
                      </el-form-item>
                      <el-form-item label="邮箱" prop="email">
                        <el-input v-model.trim="message.email"></el-input>
                      </el-form-item>
                      <el-form-item label="出生日期">
                        <el-date-picker
                          v-model.trim="message.birthday"
                          type="date"
                          placeholder="选择日期">
                        </el-date-picker>
                        <!-- <el-input v-model.trim="message.birthday"></el-input> -->
                      </el-form-item>
                      <el-form-item v-if="editMessage">
                        <el-button v-preventReClick type="primary" @click="onSubmit">保存</el-button>
                        <el-button>取消</el-button>
                      </el-form-item>
                      <el-form-item else="editMessage">
                        <el-button  type="primary" @click="dialogVisible=true;dialogData={}">修改密码</el-button>
                        <el-button v-preventReClick @click="updateUserMessage">修改信息</el-button>
                      </el-form-item>
                    </el-form>
                </div>
            </el-col>
        </el-row>
        <el-dialog
          title="修改密码"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose">
          <el-form  ref="userForm" :model="dialogData" :rules="Rules" label-width="80px">
                <el-form-item prop="oldPassword" label="旧密码">
                    <el-input
                      :key="passwordType"
                      ref="oldPassword"
                      v-model="dialogData.oldPassword"
                      :type="passwordType"
                      placeholder="Password"
                      name="oldPassword"
                      tabindex="2"
                      
                      @keyup.enter.native="updatePass"
                    />
                </el-form-item>
                <el-form-item prop="newPassword" label="新密码">
                    <el-input
                      :key="passwordType"
                      ref="newPassword"
                      v-model="dialogData.newPassword"
                      :type="passwordType"
                      placeholder="Password"
                      name="newPassword"
                      tabindex="2"
                      @keyup.enter.native="updatePass"
                    />
                </el-form-item>
                <el-form-item prop="repePassword" label="确认密码">
                   <el-input
                    :key="passwordType"
                    ref="repePassword"
                    v-model="dialogData.repePassword"
                    :type="passwordType"
                    placeholder="Password"
                    name="repePassword"
                    tabindex="2"
                    @keyup.enter.native="updatePass"
                  />
                </el-form-item>
                
                <el-form-item >
                </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button v-preventReClick type="primary" @click="updatePass">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 上传图片 -->
        <image-cropper
      v-show="imagecropperShow"
      :key="imagecropperKey"
      :width="300"
      :height="300"
      lang-type="en"
      field="avator"
      @crop-success="uploadPic"
      @close="close"
      @crop-upload-success="cropSuccess"
    />
    </div>
</template>
<script>
// import { defineComponent } from '@vue/composition-api'
import { updateUserMessage} from '@/api/user'
import ImageCropper from '@/components/ImageCropper'
import {uploadPic} from '@/api/files'
import {disposeDict} from '@/utils/dicts'

// import PanThumb from '@/components/PanThumb'
export default {
  components: { ImageCropper,  },
    data() {
       const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        // callback(new Error('Please enter the correct user name'))
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
       if (!value) {
        callback(new Error('密码不能为空'))

       }
      if (value.length < 6) {
        // callback(new Error('The password can not be less than 6 digits'))
        callback(new Error('密码不能小于6位'))
      } else {
        callback()
      }
    }
    const validateRepePassword = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        }else if (value!==this.dialogData.newPassword) {
        callback(new Error('两次密码不一致，请重新输入'))
        // callback(new Error('密码不能小于6位'))
      } else {
        callback()
      }
    }
      return{
          text:"测试",
          editMessage:false,
          passwordType:'password',
      imagecropperKey: 0,
          role:disposeDict('role','obj'),
          // sex:disposeDict('sex','obj'),
         dialogData:{},
         imagecropperShow:false,
          message:{
          },
          Rules:{
             telPhone: [
			    { required: true, message: '请输入手机号', trigger: 'blur' },
			    {
			        pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
			        message: '请输入正确的手机号码或者座机号',
			    },
			],
       email: [
			    { required: true, message: '请输入邮箱', trigger: 'blur' },
			    {
			        pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
			        message: '请输入正确的邮箱地址',
			    },
			],
        regUsername: [{ required: true, trigger: 'blur', validator: validateUsername }],
        newPassword: [{ required: true, trigger: 'blur', validator: validatePassword }],
        oldPassword: [{ required: true, trigger: 'blur', validator: validatePassword }],
        repePassword:[{ required: true, trigger: 'blur', validator: validateRepePassword }],
      },
          formData:{},
          userMessage:{},
          dialogVisible:false
      }  
    },
    created(){
    this.$store.dispatch('user/getInfo').then(res=>{
        this.message=res[0]
     })
    },
    mounted(){
    },
    methods:{
       cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.image = resData.files.avatar
      console.log(this.image)
    },
      close(){
        this.imagecropperShow=false
      },
      changeIcon(){

      },
      uploadPic(base64,fileName){
        
        uploadPic({base64,fileName}).then(res=>{
          this.$store.dispatch('user/getInfo').then(res=>{
        this.message=res[0]
     })
          // this.message.avatar=res.data.avatar+'?' + new Date().getTime();
          console.log(this.message)
        })
      },
      //修改信息
      updateUserMessage(){
        this.$refs['formData'].validate((valid) => {
          if (valid) {

            updateUserMessage(this.message).then(res=>{
        this.$message({ 
          message: '修改成功',
          type: 'success'
        });
      })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
        
      },
      
      //查看详情
      handleClick(data){
        this.dialogVisible=true
        
        this.userMessage=data
      },
      //关闭弹出框
      handleClose(){
        this.dialogVisible = false
      },
      async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login`)
    },
    updatePass() {
      
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.loading = true
          //校验成功跳转
          this.$store.dispatch('user/updatePassword', this.dialogData).then((res) => {
            console.log(res)
             this.$message({
              message: res.message,
              type: 'success'
            });
            setTimeout(() => {
              this.logout()
            }, 1000);
            
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
      
      
    }
}
</script>
<style lang='scss' scoped>
#userPermission{
    padding: 20px 0;
    
}
.el-date-editor.el-input, .el-date-editor.el-input__inner{
      width: 100%!important;
    }
.el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    // background: #99a9bf;
  }
  .bg-purple {
    // background: #d3dce6;
  }
  .bg-purple-light {
    // background: #e5e9f2;
  }
  .permission-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  .avatar{
    width: 120px;
    height: 120px;
    border-radius: 50%;
    margin-left: 150px;
    cursor: pointer;
    background: gray;
    overflow: hidden;
    img{
      width: 100%;
      height: 100%;
    }
  }
</style>